<template>
  <!-- 添加和修改轮播图表单 -->
  <el-dialog :visible.sync="dialogVisible" :title="title" @close="close">
    <el-form
      ref="adForm"
      :rules="adFormRules"
      status-icon
      :model="ad"
      label-width="120px"
      label-position="right">

      <!-- 轮播图图片 -->
      <el-form-item label="轮播图片">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :on-success="handleAdSuccess"
          accept=".jpg"
          :before-upload="beforeAdUpload"
          :action="BASE_API +'/oss/teacher/file/upload?host=ad'">
          <img v-if="ad.pic" :src="ad.pic" class="pic">
          <i v-else  class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>


      <el-form-item label="跳转课程" prop="courseName">
        <el-select
          style="width: 500px"
          v-model="ad.courseId"
          filterable
          remote
          reserve-keyword
          placeholder="请输入课程关键字进行搜索"
          :remote-method="remoteMethod"
          :loading="loading">
          <el-option
            v-for="item in courseList"
            :key="item.courseId"
            :label="item.courseName"
            :value="item.courseId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="轮播图标题" prop="name">
        <el-input v-model="ad.name" maxlength="30" show-word-limit style="width: 500px"/>
      </el-form-item>

      <el-form-item label="轮播图排序">
        <el-input-number v-model="ad.sort" :min="0" :max="999"/>
      </el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" @click="saveOrUpdate">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { getAdById, updateAdById, saveAd } from '@/api/ad'
  import { searchCourse,getCourseNameById } from '@/api/course'
  import { validNormal} from '@/utils/validate'

  export default {
    data() {
      //检验标题
      const validateName = (rule, value, callback) => {
        if (value.length < 3 || value.length > 30 || !value || !validNormal(value)){
          callback(new Error("请输入正确的标题，长度要求为5-30，且不能输入特殊字符"))
        }
        else callback()
      }

      //检验跳转
      const validateCourseName = (rule, value, callback) => {
        if (this.ad.courseId.length !== 19){
          callback(new Error("请选择轮播图需跳转的课程"))
        }
        else callback()
      }


      return {
        title: '', //dialog标题
        BASE_API: process.env.VUE_APP_BASE_API,  //后端api地址
        dialogVisible: false,
        loading: false,
        courseList: [],
        ad: {  // 轮播图对象
          id: '',
          name: '',
          courseId: '',
          courseName: '',
          sort: 0,
          pic: ''
        },
        //排序规则
        adFormRules:{
          courseName:[{validator: validateCourseName,trigger: ['blur','change']}],
          name:[{validator: validateName,trigger: 'blur'}],
        }
      }
    },

    methods: {
      open(adId) {
        this.dialogVisible = true
        if (adId) {
          this.title = '修改轮播图'
          getAdById(adId).then(result => {
            this.ad = result.data.item
            delete this.ad.gmtCreate
            delete this.ad.gmtModified
            getCourseNameById(this.ad.courseId).then(result => {
              this.courseList = []
              let course = {"courseId":this.ad.courseId,"courseName":result.data.item.name}
              this.courseList.push(course);
            })
          })
        }
        else {
          this.title = '新增轮播图'
        }
      },

      close() {
        this.$refs.adForm.resetFields();
        this.dialogVisible = false
        // 重置表单
        this.resetForm()
      },

      saveOrUpdate() {
        this.$refs.adForm.validate((valid) => {
          if (valid && this.ad.pic !== '' && this.ad.pic !== undefined) {
            //检验通过
            if (!this.ad.id) {
              this.save()
            } else {
              this.update()
            }
          }
          else {
            this.$message.error("请检查轮播图信息是否填写正确！")
            return false;
          }
        })
      },

      resetForm() {
        this.ad.id = ''
        this.ad.name = ''
        this.ad.sort = 0
        this.ad.pic = ''
        this.ad.courseId = ''
        this.ad.courseName = ''
        this.courseList = []
      },

      save() {
        getCourseNameById(this.ad.courseId).then(result => {
          this.ad.courseName = result.data.item.name
          saveAd(this.$qs.stringify(this.ad)).then(result => {
            this.$message({
              type: 'success',
              message: '保存成功！'
            })
            // 关闭组件
            this.close()
            // 调用父组件监听函数
            this.$emit('onSaveSuccess')
          })
        })
      },

      update() {
        getCourseNameById(this.ad.courseId).then(result => {
          this.ad.courseName = result.data.item.name
          updateAdById(this.ad.id, this.$qs.stringify(this.ad)).then(result => {
            this.$message({
              type: 'success',
              message: '修改成功！'
            })
            // 关闭组件
            this.close()
            // 调用父组件监听函数
            this.$emit('onSaveSuccess')
          })
        })
      },

      handleAdSuccess(res, file){
        this.ad.pic = res.data.item.url
        this.$message({
          type: 'success',
          message: '上传成功！'
        })
      },

      beforeAdUpload(file){
        const isJPG = file.type === 'image/jpeg'
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          this.$message.error('上传轮播图片只能是 JPG 格式！')
        }
        if (!isLt2M) {
          this.$message.error('上传轮播图片大小不能超过 2MB！')
        }
        return isJPG && isLt2M
      },

      //课程搜索
      remoteMethod(query){
        if (query != ''){
          this.loading = true;
          setTimeout(() => {
            this.loading = false;
            searchCourse(query).then(result => {
              let { code, data } = result
              if (code === 20000){
                this.courseList = data.item
              }
            })

          }, 200);
        }
        //搜索为空
        else {
          this.courseList = []
        }
      }
    }
  }
</script>

<style scoped>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .pic {
    max-width: 500px;
    display: block;
    object-fit: fill;
  }
</style>
